#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import shutil
import subprocess
from pathlib import Path

def check_pyinstaller():
    """检查是否安装了PyInstaller"""
    try:
        subprocess.run([sys.executable, "-m", "PyInstaller", "--version"], 
                       capture_output=True, check=True)
        return True
    except (subprocess.CalledProcessError, FileNotFoundError):
        return False

def install_pyinstaller():
    """安装PyInstaller"""
    print("正在安装PyInstaller...")
    try:
        subprocess.run([sys.executable, "-m", "pip", "install", "pyinstaller"], 
                       check=True)
        print("PyInstaller安装成功")
        return True
    except subprocess.CalledProcessError as e:
        print(f"PyInstaller安装失败: {e}")
        return False

def build_executable():
    """构建可执行文件"""
    print("开始构建可执行文件...")
    
    # 构建命令
    cmd = [
        sys.executable, "-m", "PyInstaller",
        "--name", "GitBackupTool",
        "--onefile",  # 打包成单个文件
        "--windowed",  # 无控制台窗口
        "--icon=assets/icon.ico",  # 图标文件（如果存在）
        "--add-data=ui;ui",  # 包含ui目录
        "--add-data=core;core",  # 包含core目录
        "--add-data=config;config",  # 包含config目录
        "--add-data=utils;utils",  # 包含utils目录
        "--add-data=assets;assets",  # 包含assets目录
        "main.py"
    ]
    
    # 检查图标文件是否存在，如果不存在则移除图标参数
    if not os.path.exists("assets/icon.ico"):
        cmd = [arg for arg in cmd if not arg.startswith("--icon")]
    
    # 创建assets目录（如果不存在）
    if not os.path.exists("assets"):
        os.makedirs("assets")
    
    # 创建空的__init__.py文件
    for dir_name in ["ui", "core", "config", "utils"]:
        init_file = os.path.join(dir_name, "__init__.py")
        if not os.path.exists(init_file):
            with open(init_file, "w", encoding="utf-8") as f:
                f.write("#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n")
    
    try:
        subprocess.run(cmd, check=True)
        print("可执行文件构建成功")
        return True
    except subprocess.CalledProcessError as e:
        print(f"可执行文件构建失败: {e}")
        return False

def create_portable_package():
    """创建便携版包"""
    print("正在创建便携版包...")
    
    # 创建发布目录
    release_dir = "release"
    if os.path.exists(release_dir):
        shutil.rmtree(release_dir)
    
    os.makedirs(release_dir)
    
    # 复制可执行文件
    if os.path.exists("dist/GitBackupTool.exe"):
        shutil.copy("dist/GitBackupTool.exe", release_dir)
    
    # 复制其他必要文件
    other_files = [
        "README.md",
        "LICENSE"
    ]
    
    for file in other_files:
        if os.path.exists(file):
            shutil.copy(file, release_dir)
    
    # 创建配置目录
    os.makedirs(os.path.join(release_dir, "config"))
    os.makedirs(os.path.join(release_dir, "logs"))
    
    # 创建批处理启动文件
    with open(os.path.join(release_dir, "start.bat"), "w", encoding="utf-8") as f:
        f.write("@echo off\n")
        f.write("title Git备份工具\n")
        f.write("echo 正在启动Git备份工具...\n")
        f.write("GitBackupTool.exe\n")
        f.write("pause\n")
    
    # 创建便携版说明文件
    with open(os.path.join(release_dir, "便携版说明.txt"), "w", encoding="utf-8") as f:
        f.write("Git备份工具 - 便携版\n\n")
        f.write("使用说明:\n")
        f.write("1. 双击 start.bat 或直接运行 GitBackupTool.exe 启动程序\n")
        f.write("2. 首次运行时，程序会在当前目录创建配置文件和日志文件\n")
        f.write("3. 所有配置和日志都保存在程序的config和logs目录中\n")
        f.write("4. 可以将整个文件夹复制到其他位置使用\n\n")
        f.write("注意事项:\n")
        f.write("- 请确保系统已安装Git并配置好环境变量\n")
        f.write("- 备份大文件时请确保网络连接稳定\n")
        f.write("- 建议定期清理日志文件以节省磁盘空间\n")
    
    # 创建ZIP压缩包
    try:
        import zipfile
        zip_name = "GitBackupTool_Portable.zip"
        with zipfile.ZipFile(zip_name, "w", zipfile.ZIP_DEFLATED) as zipf:
            for root, dirs, files in os.walk(release_dir):
                for file in files:
                    file_path = os.path.join(root, file)
                    arcname = os.path.relpath(file_path, release_dir)
                    zipf.write(file_path, arcname)
        
        print(f"便携版包创建成功: {zip_name}")
        return True
    except Exception as e:
        print(f"创建便携版包失败: {e}")
        return False

def main():
    """主函数"""
    print("Git备份工具 - 构建脚本")
    print("=" * 40)
    
    # 检查Git是否安装
    try:
        subprocess.run(["git", "--version"], capture_output=True, check=True)
        print("Git已安装")
    except (subprocess.CalledProcessError, FileNotFoundError):
        print("警告: 未检测到Git，请确保目标系统已安装Git")
    
    # 检查PyInstaller
    if not check_pyinstaller():
        print("PyInstaller未安装，正在安装...")
        if not install_pyinstaller():
            print("无法安装PyInstaller，构建失败")
            return
    
    # 构建可执行文件
    if not build_executable():
        print("构建可执行文件失败")
        return
    
    # 创建便携版包
    if not create_portable_package():
        print("创建便携版包失败")
        return
    
    print("=" * 40)
    print("构建完成！")
    print(f"可执行文件位置: dist/GitBackupTool.exe")
    print(f"便携版包位置: GitBackupTool_Portable.zip")
    print("=" * 40)

if __name__ == "__main__":
    main()